//
//  SplashScreenViewController.m
//  Seizure
//
//
//  Home/Default screen for registering/logging in

#import "SplashScreenViewController.h"
#import "SetupViewController.h"
#import "PatientTabViewController.h"
#import "CaretakerTabViewController.h"
#import "LocalData.h"
#import "DataManager.h"
#import "Account.h"
#import "AppDelegate.h"

@implementation SplashScreenViewController

@synthesize email;
@synthesize password;
UIAlertView *loadingAlert;
static short loginRequest = 0;


#pragma mark -
#pragma mark Login Screen
/**
 * Process a user login. Check to see if they are valid and retrieve nessecary information.
 */
- (IBAction) processLoginRequest: (id) sender
{
    
    if(email.text.length == 0 || password.text.length == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Login Information" message:@"Fill out the requested fields." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }
    else 
    {
        DataManager *dm = [DataManager sharedInstance];
        
        // send account creation request
        [dm loginUser:email.text password:password.text delegate:self requestType:loginRequest];
        
        
        // popup a dialog while this controller <NetworkData> awaits a response
        loadingAlert = [DBCommunicator createLoadingAlert];
        [loadingAlert show];
    }
}

/**
 *  Resets the user's password by using the email entered into the email TextField. Sends an email containing a link to change their password.
 */
- (IBAction) resetPassword:(id)sender
{
    DataManager *dm = [DataManager sharedInstance];
    UIAlertView *alert;
    if( [dm resetPassword:email.text] )
        alert = [[UIAlertView alloc]initWithTitle:@"Success!" message:@"An email has been sent to the provided email with a link and instructions to reset your password" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
    else
        alert = [[UIAlertView alloc]initWithTitle:@"Failed..." message:@"An email has NOT been sent to the provided email. Please check the spelling and that you have a connection to the internet and try again." delegate:nil cancelButtonTitle:@"Okay..." otherButtonTitles: nil];
    [alert show];
}

// Login as Patient with a fake account [email = "NULL"]
- (IBAction) useWithoutAccount:(id)sender{
    DataManager *dm = [DataManager sharedInstance];
    
    // create and store a fake account for detection only
    [dm createFakeAccount];
    
    UITabBarController *patientController = [[PatientTabViewController alloc] initWithNibName:@"PatientTabViewController" bundle:nil];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self.navigationController pushViewController:patientController animated:YES];
    
}

/**
 * Send the user to the registration page
 */
- (IBAction) toCreateAccountView: (id)sender
{
    //Set the "back" button to Cancel instead
    UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:@"Cancel"
                                                                     style:UIBarButtonItemStylePlain 
                                                                    target:nil
                                                                    action:nil];
    self.navigationItem.backBarButtonItem = cancelButton;
    
    SetupViewController *setupView = [[SetupViewController alloc] initWithNibName:@"SetupViewController"
                                                                           bundle:nil];
    [self.navigationController pushViewController:setupView animated:YES];
}

//Go to the next field if they hit return
- (BOOL) textFieldShouldReturn: (UITextField *) textField{
    [self nextPressed: textField];
    
    return YES;
}

/**
 * What the keyboard should do if next is pressed
 */
- (void) nextPressed: (id) sender
{    
    if( [email isFirstResponder] ) // from email -> goto password
        [password becomeFirstResponder];
    
    else if( [password isFirstResponder] ) // from password -> hide keyboard
        [self processLoginRequest:nil];
}

/**
 *  When the background is touch, get rid of keyboard.
 */
- (IBAction) backgroundTouched: (id) sender
{
    [email becomeFirstResponder];
    [email resignFirstResponder];
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


#pragma mark -
#pragma mark NetworkData

// retrieve login response back (login is only request this controller sends)
-(void)DataArrived:(id)dataObject requestType:(int)rtype {
    dispatch_async(dispatch_get_main_queue(), ^(void) {
        
        [loadingAlert dismissWithClickedButtonIndex:0 animated:YES];
        loadingAlert = nil;
        
        if (dataObject == nil){
            // something went wrong, probably no internet connection
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Failed to Login!" message:@"The application was unable to log you in. Please check that you have data enabled or have an active internet connection." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
        }
        else if (rtype == loginRequest){
            Account *user = (Account*)dataObject;
            DataManager *dm = [DataManager sharedInstance];
            [dm storeAccount:user];
            
            // Update APNS key (AppDelegate is notified)
            AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
            [delegate updateAPNSKey];
            
            UITabBarController *nextController;
            if(user.isPatient )
            {
                nextController = [[PatientTabViewController alloc] initWithNibName:@"PatientTabViewController" bundle:nil];
            }
            else
            {
                nextController = [[CaretakerTabViewController alloc] initWithNibName:@"CaretakerTabViewController" bundle:nil];
            }
            
            [self.navigationController setNavigationBarHidden:YES animated:YES];
            [self.navigationController pushViewController:nextController animated:YES];
            
            
        }
    }); 
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    [email setAutocorrectionType:UITextAutocorrectionTypeNo];
    [email setAutocapitalizationType:UITextAutocapitalizationTypeNone];
    
    Account *acc = [[DataManager sharedInstance] getStoredAccount];
    
    // check if we have a local account to auto-login
    if (acc != nil){
        
        [self.navigationController  setNavigationBarHidden:YES animated:YES];
        
        if ([acc isPatient]){  
            
            PatientTabViewController *newController = [[PatientTabViewController alloc] initWithNibName:@"PatientTabViewController" bundle:nil];
            [self.navigationController pushViewController:newController animated:YES];
        }
        else {
            
            CaretakerTabViewController *newController = [[CaretakerTabViewController alloc] initWithNibName:@"CaretakerTabViewController" bundle:nil];
            [self.navigationController pushViewController:newController animated:YES];
        }
    }
    else
    {
        // no account found
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
